<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            height: 200px;
            width: 200px;
            background-color: greenyellow;
            text-align: center;
            padding: 20px;
            box-sizing: border-box;
            margin: 10px;
        }

        #weather {
            display: flex;
            flex-wrap: wrap;
        }
    </style>
</head>

<body>
    <div id="weather">
    </div>
</body>

</html>

<script src="./js/14.ajax-promise的封装.js"></script>
<script>
    const getWeather = () => ajax({ //获取天气的api
        url: "http://chst.vip/weather/getWeather",
        data: { key: 'all' }
    })

    getWeather()
        .then((res) => {
            let contenEnd = 420
            let needArray = res.data.slice(400, contenEnd)
            draw(needArray)
            document.onscroll = debounce(function () {
                let clientHeight = document.documentElement.clientHeight;
                let scrollHeight = document.documentElement.scrollHeight;
                let scrollTop = document.documentElement.scrollTop;
                //计算阈值
                let threshold = scrollHeight - (scrollTop + clientHeight);

                if (threshold <= 100) {
                    setTimeout(function () {
                        contenEnd += 20
                        needArray = res.data.slice(400, contenEnd)
                        draw(needArray)
                    }, 1000)
                }
            }, 200)
        })


// 创建元素
    function draw(needArray) {
        let html = ''
        needArray.forEach(item => {
            html += `<div class="box">
                            <p> ${item.date}</p>
                            <p> ${item.tem} oC</p>
                            <p> ${item.week}</p>
                            <p> ${item.city}</p>
                        </div>`
        });
        weather.innerHTML = html
    }


// 防抖
    function debounce(fn, tick) {
        let timer = 0
        return function () {
            fn = fn.bind(this)
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                fn()
            }, tick);
        }
    }
</script>